define([
	"jquery",
	"template",
	"oms_tpl/navbar.tpl",
	"oms_model/navbar",
	"oms_config/config",
	"comm/toast/toast"],
function($,$template,tpl,Account,$config,$toast){
	var defaults,navbar = {};

	$.ajaxSetup({
	    async:true
	});

	/**
	 * 初始化全局菜单栏数据
	 * 如果传入新数据，则更新
	 */
	var initData = function(params){
		if(params.navs){
			defaults = {
				navs:params.navs
			}
			$("#left-navbar").data("navs",params.navs);
		}else{
			defaults = {
				navs:$("#left-navbar").data("navs")
			}
		}
	}

	/**
	 * 根据名称获取(广度逐层搜索)
	 */
	var getNavbarData = function(name,navs,config){
		if(navs&&navs.length>0){
			var childrens = [];
			for(var i=0;i<navs.length;i++){
				_config = typeof navs[i].config == "string" ? navs[i].config : JSON.stringify(navs[i].config);

				if( (navs[i].name==name && !config && !_config) ||
					(navs[i].name==name && config && _config==config) ){
					return navs[i];
				}else if( (navs[i].name==name && !config) ){ // 权宜之计
					return navs[i];
				}else if(navs[i].childrens && navs[i].childrens.length>0){
					childrens = childrens.concat(navs[i].childrens);
				}
			}
			if(childrens.length>0){
				return getNavbarData(name,childrens,config);
			}
		}
	}

	/**
	 * 根据id获取(广度逐层搜索)
	 */
	var getNavData = function(id,navs){
		if( navs && navs.length > 0){
			var childrens = [];
			for( var i=0; i< navs.length; i++ ){
				if( navs[i].id == id ){
					return navs[i];
				}else if( navs[i].childrens && navs[i].childrens.length > 0 ){
					childrens = childrens.concat(navs[i].childrens);
				}
			}
			if( childrens.length > 0 ){
				return getNavData(id,childrens);
			}
		}
	}

	/**
	 * 刷新面包屑
	 */
	var refreshCrumb = function(){
		var crumbs = $("#left-navbar").data("crumbs");
		tpl.initCrumb("crumbs");
		$('#crumbs').html($template("tpl_crumb",{crumbs:crumbs}));
	}

	/**
	 * 添加面包屑
	 */
	var addCrumb = function(data){
		var crumbs = $("#left-navbar").data("crumbs");
		var tag = true;
		for(var i=0;i<crumbs.length;i++){
			if(data&&data.name==crumbs[i].name){
				tag = false;
				crumbs.length = i+1;
				break;
			}
		}
		if(tag){
			var i = crumbs.length;
			crumbs[i] = data;
		}
		$("#left-navbar").data("crumbs",crumbs);
		refreshCrumb();
	}

	/**
	 * 重置面包屑
	 */
	var resetCrumb = function(navbar){
		var navs = $("#left-navbar").data("navs");
		var list = navbar.parents("li:not(:first)").children("a");
		var crumbs = [];
		for(var i=0;i<list.length;i++){
			crumbs[i] = {};
			var name = $(list[i]).attr("data-name");
			var config = $(list[i]).attr("data-config");
			crumbs[i] = getNavbarData(name,navs,config);
		}
		$("#left-navbar").data("crumbs",crumbs);
	}

	/**
	 * 打开加载提示
	 */
	var openLoading = function(){
		tpl.initLoading("content-main");
		$('#content-main').html($template("tpl_loading",{}));
	}

	/**
	 * 加载出错
	 */
	var loadError = function(code){
		var data = {};
		switch (code) {
			case 0:
				data.content = '网络连接异常，请检查网络！';
				break;
			case 404:
				data.content = '没有找到页面，请试试别的操作！';
				break;
			case 500:
				data.content = '服务器内部错误，请联系运维！';
				break;
		default:
			break;
		}
		tpl.initError("content-main");
		$('#content-main').html($template("tpl_error",data));
	}
	function Router() {
		this.routes = {}
		this.init()
	}
	Router.prototype.init = function () {
		var _this = this
		window.addEventListener('hashchange', function(event) {
			var HASH = event.newURL.split('#/')[1]
			_this.routes[HASH].render()
		}, false)
	}
	Router.prototype.push = function (flag, name, config, params, callback) {
		window.location.hash = '/' + name

		this.routes[name] = {
			flag: flag,
			name: name,
			config: config,
			params: params,
			callback: callback,
			render: function() {
				// openPage(this.flag, this.name, this.config ? this.config : '')
				this.callback(this.params)
			}
		}
	}
	Router.prototype.jump = function (name) {
		var flag = this.routes[name].flag
		var config = this.routes[name].config
		openPage(flag, name, config ? config : '')
		this.routes[name].callback(this.routes[name].params)
	}
	var router = new Router()

	/**
	 * 打开页面
	 */
	var openPage = function(flag,name,config){
		//if(defaults.loadPageLocked) return;
		defaults.loadPageLocked = true;
		$('#content-main').removeData("params");
		var navs = $("#left-navbar").data("navs");
		if( flag == "byName"){
			var data = getNavbarData(name,navs,config);
		}else if( flag == "byId"){
			var data = getNavData(name,navs); // 此name实际为id
		}
		// console.log('data',data)
		if(!data)return;
		addCrumb(data);
		emptyContextmenu();
		emptyTopbar();
		openLoading();
		$.get(data.url,function(ret){
			$toast.close(); // 解决 门诊录入在校验中，点击nav跳转时出现的弹框bug
			var pageParam = $('#content-main').data("params");
			if( !data.params ) data.params = {};						 // 资源表里配置的参数
			if( data.config ){ // 菜单表里的参数
				if( typeof data.config == "string" ){
					data.config = JSON.parse(data.config);
				}else{
					data.config = data.config;
				}
			}else{
				data.config = {};
			}
			if( !pageParam ) pageParam = {};					 // 一个页面跳转到另一个页面传递的参数
			var params = $.extend({},data.params,data.config,pageParam);
			router.push(flag, name, config, params, function (param) {
				$('#content-main').data("params",param);
			})
			$('#content-main').data("params",params);
			$('#content-main').html(ret);
			$config.textByLanguageKey();
			$config.domControlDisplay();
			defaults.loadPageLocked = false;
		}).error(function(xhr, textStatus, errorThrown){
			if(xhr.readyState<4){
				loadError(0)
			}else{
				loadError(xhr.status);
			}
			defaults.loadPageLocked = false;
		});
	}

	/**
	 * 菜单被点击选中事件
	 */
	var onSelect = function(){
		var _this = $(this);
		var leaf = _this.attr("data-type")=="leaf";
		if(leaf){
			var name = _this.attr("data-name");
			var config = _this.attr("data-config");
			$("#left-navbar li").removeClass("active");
			_this.parents("li").addClass("active");
			_this.parents("li").children("ul").addClass("open");
			resetCrumb(_this);
			emptyTopbar();
			openPage("byName",name,config);
		}else{
			_this.next().toggleClass("open");
			_this.find(".pull-right").toggleClass("fa-angle-right");
			_this.find(".pull-right").toggleClass("fa-angle-down");
		}
	}
	var onBreadcrumbli = function() {
		let data = $(this).data()
		if (data.name && data.name != '') {
			router.jump(data.name)
		}
	}

	/**
	 * 重新初始化导航菜单，慎调
	 */
	navbar.init = function(params){
		initData(params);
		//初始化应用菜单
		tpl.init("left-navbar");
		$('#left-navbar').html($template("tpl_navbar",{childrens:defaults.navs}));
		$('#left-navbar a').click(onSelect);
		$('#left-navbar [data-type=leaf]').first().click();
		$('#crumbs').delegate('li', 'click', onBreadcrumbli)
	}

	/**
	 * 选中一个导航菜单并打开导航页面
	 * param:
	 * 	name:导航菜单的名称
	 */
	navbar.select = function(name,config){
		if(config){
			var dom = $('#left-navbar [data-name='+name+']');
			for (var i = 0; i < dom.length; i++) {
				if( dom[i].dataset.config == config ){
					dom[i].click();
				}
			}
		}else{
			$('#left-navbar [data-name='+name+']').click();
		}
	}

	/**
	 * 打开一个新页面，但导航菜单保持不变
	 * param:
	 * 	name:导航菜单的名称
	 */
	navbar.openPage = function(name,config){
		openPage("byName",name,config);
	}

	/**
	 * 打开一个新页面
	 * param:
	 * 	id:租户下导航菜单的id
	 */
	navbar.fopen = function(id){
		openPage("byId",id);
	}

	/**
	 * 页面右上角按钮组
	 */
	navbar.topbar = function(topbars){
		tpl.initTopbar("topbar");
		$('#topbar').html($template("tpl_topbar",{topbars:topbars}));
	}

	/**
	 * 清空 topbar
	 */
	var emptyTopbar = function(){
		$('#topbar').html("");
	}

	/**
	 * 清空 右键
	 */
	var emptyContextmenu = function(){
		$("#contextmenu").html("");
	}

	return navbar;
});
